package youtube.tv

import java.util.List;

class YoutubeService {

  static transactional = false
  
  def maxResultCount = 30

  def getVideos(VideoCategory videoCategory, int startIndex) {
	// getDummyVideos(feed, startIndex)
    getVideosFromYoutube(videoCategory, startIndex)
  }
  
  def getVideos(VideoCategory videoCategory, int startIndex, String videoId) {
    // getDummyVideos(feed, startIndex)
    def res = getVideosFromYoutube(videoCategory, startIndex)
	if(videoId){
	  def currentVideoInfo = getVideoFromYoutube(videoId)
      if(res){
        res[0] = currentVideoInfo
      }
	  else{
		res = [currentVideoInfo]
	  }
    }
	return res
  }
  
  def getDummyVideos(String feed, String startIndex) {
    [[id:'osa1']]
  }
  def getVideoFromYoutube(String videoId) {
	def url = "http://gdata.youtube.com/feeds/api/videos/${videoId}"
    def slurp = new XmlSlurper()
    log.error "Calling Youtube: $url"
    def mediaNamespace = new groovy.xml.Namespace('http://search.yahoo.com/mrss/')
    def entry = new XmlParser().parse(new URL(url).openStream())
    return [id: videoId, title: entry.title.text(),
            thumbnail : entry[mediaNamespace.group][mediaNamespace.thumbnail][0].@url]
  }

  def getVideosFromYoutube(VideoCategory videoCategory, int startIndex) {
    def rssurl = "http://gdata.youtube.com/feeds/api/${videoCategory.feed}?max-results=${maxResultCount}"
	if(startIndex){
		rssurl += "&start-index=${startIndex + 1}"
	}
	if(videoCategory.time){
		rssurl += "&time=${videoCategory.time}"
	}
    def slurp = new XmlSlurper()
	log.error "Calling Youtube: $rssurl"
	def mediaNamespace = new groovy.xml.Namespace('http://search.yahoo.com/mrss/')
    def rss = new XmlParser().parse(new URL(rssurl).openStream())
    List res = []
    rss.entry.each { entry ->
      def matcher = entry.id.text() =~ /\/([\-\w]+)$/
      if(matcher){
        def thumbnails = entry[mediaNamespace.group][mediaNamespace.thumbnail]
        res << [id: matcher[0][1], title: entry.title.text(),
			    thumbnail : (thumbnails ? thumbnails[0].@url : null)]
      }else
        log.warn "Failed to parse id from ${entry.id}"
	}
	//log.error "RESULT: $res"
	return res
  }
}
